import { Component, OnInit, ElementRef, ViewChild, ViewChildren, AfterViewInit, Renderer, SimpleChanges, OnDestroy } from '@angular/core';
import { DataSourceService } from '../../../service/data-source/data-source.service';
import { ApplicationService } from '../../../service/application.service';
import { Farm } from '../../../entity/farm.model';
import { TagData } from '../../../entity/tag-data.model';
import { DatePipe } from '@angular/common';
import { Tag } from '../../../entity/tag.model';
import { List } from 'linqts';
import { Table, TableRow, TableColomn, TableCell } from '../../monitor/turbine-data-list/table.model';
import { Device } from '../../../entity/device.model';
import { FarmCategoryEnum } from '../../common/device-tag-selector/farm-category.enum';
import { DeviceCategoryEnum } from '../../common/device-tag-selector/device-category.enum';

@Component({
  selector: 'app-turbine-operation',
  templateUrl: './turbine-operation.component.html',
  styleUrls: ['./turbine-operation.component.css']
})
export class TurbineOperationComponent implements OnInit {
  public farmCategory = FarmCategoryEnum.winfarm;
  public deviceCategory: DeviceCategoryEnum[] = [DeviceCategoryEnum.turbine];

  /**
  * table td元素集合
  *
  * @type {ElementRef[]}@memberof TurbineOperationComponent
  */
  @ViewChildren('td')
  private td: ElementRef[];
  /**
 * table th元素集合
 *
 * @type {ElementRef[]}@memberof TurbineOperationComponent
 */
  @ViewChildren('th')
  private th: ElementRef[];
  /**
  * table元素集合
  *
  * @type {ElementRef[]}@memberof TurbineOperationComponent
  */
  @ViewChild('main')
  private main: ElementRef;
  private fomat = 'yyyy-MM-dd HH:00';
  /**
   * 开始时间
   *
   * @type {Date}
   * @memberof TurbineOperationComponent
   */
  startDate: Date;

  /**
   * 风场运行温度统计集合
   *
   * @type {OperatData[]}
   * @memberof TurbineOperationComponent
   */
  operatDatas: TurbOperatData[] = [];
  /**
   * 所有设备集合
   *
   * @type {Device[]}
   * @memberof TurbineOperationComponent
   */
  devices: Device[];

  /**
   * 测点集合
   *
   * @type {TagData[]}
   * @memberof TurbineOperationComponent
   */
  measuringPoint: any[] = [];
  mes: string;
  display = false;
  LimitedChoice = 0;
  totalRecords: number;
  /**
   * 测点对象集合
   *
   * @type {Tag[]}@memberof TurbineOperationComponent
   */
  tags: Tag[];
  /**
   * 展示的数据
   *
   * @type {OperatData[]}
   * @memberof TurbineOperationComponent
   */
  showOperatDatas: OperatData[] = [];
  /**
   * 默认选中测点
   *
   * @type {string[]}
   * @memberof TurbineOperationComponent
   */
  /**
   * 风机选择定时器
   *
   * @type {*}
   * @memberof TurbineOperationComponent
   */
  timer: any;
  unit: string[];
  /**
* 生成的table集合
*
* @type {Table[] }@memberof TurbineOperationComponent
*/
  public turbTable: Table[] = [];
  /**
   * 生成的table集合的th
   *
   * @type {string[]}@memberof TurbineOperationComponent
   */
  private title: string[] = [];
  /**
* 生成的table集合的row集合
*
* @type {TableRow[]}@memberof TurbineOperationComponent
*/
  private tableRow: TableRow[] = [];
  /**
   *设备选择最大数量
   *
   * @type {number}
   * @memberof TurbineOperationComponent
   */
  public deviceCountLimit: number;
  /**
   *刚进页面是默认选择风机数量
   *默认:null 不做限制
   * 0不选择
   * @memberof TurbineOperationComponent
   */
  defaultChooseDeviceCount;
  /**
   *日期格式化
   *
   * @type {*}
   * @memberof TurbineOperationComponent
   */
  en:any;
  constructor(
    private dataSource: DataSourceService,
    private application: ApplicationService,
    private datePipe: DatePipe,
    private renderer: Renderer
  ) { }

  ngOnInit() {
    this.en = {
			firstDayOfWeek: 0,
			dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
			dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
			dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
			monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
			monthNamesShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
			today: '今天',
			clear: '清除'
		};
    this.startDate = new Date(this.datePipe.transform(new Date(new Date()), this.fomat));
    if (this.application.currentMenuParams && this.application.currentMenuParams['deviceCountLimit']) {
      this.deviceCountLimit = Number(this.application.currentMenuParams['deviceCountLimit'].paramValue);
    } else {
      this.deviceCountLimit = null;
    }
    if (this.application.currentMenuParams && this.application.currentMenuParams['defaultChooseDeviceCount']) {
      this.defaultChooseDeviceCount = Number(this.application.currentMenuParams['defaultChooseDeviceCount'].paramValue);
    } else {
      this.defaultChooseDeviceCount = null;
    }
    /* if (this.application.currentMenuParams && this.application.currentMenuParams['selectTurbineCount']) {
      this.LimitedChoice = Number(this.application.currentMenuParams.selectTurbineCount.paramValue);

    } else {
      this.LimitedChoice = 1;
    } */

    this.onSearch();
  }
  // tslint:disable-next-line:use-life-cycle-interface
  public ngAfterViewChecked() {
    this.onResize();
  }
  /**
   * 得到历史数据
   *
   * @memberof TurbineOperationComponent
   */
  getData() {
    const codes: string[] = [];
    this.turbTable = [];
    this.tableRow = [];
    this.title = ['风场名称', '风机编号'];
    this.unit = [' ', ' '];
    this.tags.forEach(tag => {
      const unit: string = tag.tagUnit ? '(' + tag.tagUnit + ')' : ' ';
      this.unit.push(unit);
      this.title.push(`${tag.tagName}`);
    });
    if (this.devices != null && this.devices.length > 0) {
      const groups = new List(this.devices).GroupBy(g => g.farmCode, m => m);
      const farmCodes = Object.getOwnPropertyNames(groups);
      this.devices.forEach((turbine, index) => {
        const td: TableColomn[] = [];
        const tr: TableRow = {
          rowIndex: index,
          colomns: td,
        };
        this.tableRow.push(tr);

        // 创建风机固定信息列
        const farmName: TableColomn = {
          colomnIndex: 0,
          cell: {
            rowIndex: 0,
            colomnIndex: 0,
            data: turbine.farmName + '风场',
          },
        };
        td.push(farmName);

        const turbineName: TableColomn = {
          colomnIndex: 1,
          cell: {
            rowIndex: index,
            colomnIndex: 1,
            data: turbine.deviceName,
          },
        };
        td.push(turbineName);


        // 创建风机测点列
        // tslint:disable-next-line:no-shadowed-variable
        this.tags.forEach((tag: Tag, index: number) => {
          const point = this.dataSource.binding([turbine.farmCode, turbine.deviceCode], tag);
          codes.push(point.code);
          const tagName: TableColomn = {
            colomnIndex: index + 2,
            cell: {
              rowIndex: index,
              colomnIndex: index + 2,
              // 绑定数据
              data: point,
            }
          };
          td.push(tagName);
        });
      });
      if (this.devices.length > 0) {
        const count = 20; // table的行数
        const rows = 12; // table的列数
        const page = Math.ceil(this.tableRow.length / count);
        const pageTabel = Math.ceil(this.tableRow[0].colomns.length / rows);
        for (let i = 0; i < page; i++) {
          const tableSlice: TableRow[] = this.tableRow.slice(i * count, i * count + count);
          for (let n = 0; n < pageTabel; n++) {
            const title = n ? this.title.slice(0, 2).concat(this.title.slice(n * rows, n * rows + rows - 2)) : this.title.slice(0, rows);
            const tableSliceRows: TableRow[] = [];
            tableSlice.forEach((v, index) => {
              tableSliceRows.push({
                rowIndex: v.rowIndex,
                colomns: n ? v.colomns.slice(0, 2).concat(v.colomns.slice(n * rows, n * rows + rows - 2)) : v.colomns.slice(0, rows),
              });
            });
            this.turbTable.push({
              rows: tableSliceRows,
              th: title,
              unit: this.unit
            });
          }
        };

      }
    }
    return codes;

  }
  /**
   * 查询历史数据
   *
   * @memberof TurbineOperationComponent
   */
  onSearch() {
    if (!this.devices && !this.tags) { return false; };
    const codes = this.getData();

    const date = this.datePipe.transform(new Date(this.startDate), this.fomat);

    this.dataSource.history
      .getHistories(codes, this.startDate)
      .then(res => {

        if (!res || !res.length) { return false; };
        this.turbTable.forEach(tableData => {
          tableData.rows.forEach(row => {
            row.colomns.forEach((colomn, i) => {
              if (i <= 1) { return false; };
              const code = colomn.cell.data.code;

              const index = res.findIndex(r => r.code === code);
              if (index > -1) {
                colomn.cell.data.value = res[index].value;
                colomn.cell.data.time = res[index].time;
              }
            });
          });
        });
      })
      .catch(err => {
        console.log(err);
      });
  }


  /**
* 得到选中风场风机集合
*
* @type {limitedTurbine[]}@memberof TurbineDataListComponent
*/
  public onSelectedDevicesChange(ev: Device[]) {
    this.devices = ev;
    if (this.tags) {

      this.onSearch();

    }



  }
  selectedTagsChange(ev: Tag[]) {
    this.tags = ev;
    if (this.devices) {

      this.onSearch();

    }

  }
  loadData(event: any, index: number) {
    setTimeout(() => {
      this.showOperatDatas = this.operatDatas.slice(event.first, (event.first + event.rows));
    }, 250);

  }
  /**
* 改变table的布局
*
* @type {}@memberof TurbineDataListComponent
*/
  public onResize() {
    const mainWidth: number = this.main.nativeElement.offsetWidth - 20;
    this.th.forEach((elem, i) => {
      if (!i) {
        this.renderer.setElementStyle(elem.nativeElement, 'width', 140 + 'px');
        return false;
      }
      this.renderer.setElementStyle(elem.nativeElement, 'width', (mainWidth - 140) / 11 + 'px');
    });
    this.td.forEach((elem, i) => {
      if (!i) {
        this.renderer.setElementStyle(elem.nativeElement, 'width', 140 + 'px');
        return false;
      }
      this.renderer.setElementStyle(elem.nativeElement, 'width', (mainWidth - 140) / 11 + 'px');
    });
  }

  exportData() {
		// 使用outerHTML属性获取整个table元素的HTML代码（包括<table>标签），然后包装成一个完整的HTML文档，设置charset为urf-8以防止中文乱码
		var html = "<html><head><meta charset='utf-8' /></head><body>" + document.getElementById("ex-tab").outerHTML + "</body></html>";
		// 实例化一个Blob对象，其构造函数的第一个参数是包含文件内容的数组，第二个参数是包含文件类型属性的对象
		var blob = new Blob([html], { type: "application/vnd.ms-excel" });
    
		// var a = document.getElementsByTagName("a")[0];
		// 利用URL.createObjectURL()方法为a元素生成blob URL
		var href = URL.createObjectURL(blob);
		document.getElementById("ex").setAttribute("href", href);
		
		// // 设置文件名，目前只有Chrome和FireFox支持此属性
		document.getElementById("ex").setAttribute("download","实际功率曲线.xls"); 
		// a.download = "实际功率曲线.xls";
		// a.click();
		// document.getElementById("ex").click();
	}
}
interface OperatData {
  turbineName: string; // 风机编号
  windSpeedCode?: string;
  loadCode?: string;
  gearBoxTempCode?: string;
  gearOilTempCode?: string;
  environmentTempCode?: string;
}
interface TurbOperatData {
  turbineName: string; // 风机编号
  time?: Date; // 统计时间
  windSpeed?: number; // 风速
  load?: number; // 负荷
  gearBoxTemp?: number; // 齿轮箱前轴温度
  gearOilTemp?: number; // 齿轮油温
  environmentTemp?: number; // 环境温度
}




// WEBPACK FOOTER //
// ./src/app/module/data-analysis/turbine-operation/turbine-operation.component.ts